package com.xms.dependency.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xms.dependency.entity.Dependency;
import com.xms.dependency.model.DependentDescriptor;
import com.xms.logging.service.IAppLogging;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 依赖组件查找工厂
 * </p>
 *
 * @author migo
 * @since 2021/10/23
 */
@Service
public class DependencyLookupFactory implements IDependencyLookupFactory {
    private IDependencyFinderService _dependencyFinderService;
    private IAppLogging _appLogging;
    private List<IDependentLookup> _dependentLookups;

    @Autowired
    public DependencyLookupFactory(IDependencyFinderService dependencyFinderService,
                                   IAppLogging appLogging,
                                   List<IDependentLookup> dependentLookups)
    {
        _dependencyFinderService = dependencyFinderService;
        _appLogging = appLogging;
        _dependentLookups = dependentLookups;
    }

    /**
     * 获取依赖项清单
     * @param requiredComponentType 被依赖的对象类型
     * @param requiredId 被依赖组件类型
     * @return
     */
    @Override
    public List<DependentDescriptor> getDependents(int requiredComponentType, UUID requiredId)
    {
        List<DependentDescriptor> result = new ArrayList<>();
        try
        {
            List<Dependency> dependents = _dependencyFinderService.list(new LambdaQueryWrapper<Dependency>().eq(Dependency::getRequiredcomponenttype, requiredComponentType)
                    .eq(Dependency::getRequiredobjectid, requiredId));
            for (Dependency item : dependents)
            {
                IDependentLookup finder = _dependentLookups.stream().filter(x -> x.getComponentType() == item.getDependentcomponenttype()).findFirst().orElse(null);
                if (finder != null)
                {
                    DependentDescriptor dependentDescriptor = finder.getDependent(item.getDependentobjectid());
                    if (dependentDescriptor != null)
                    {
                        dependentDescriptor.componentType = item.getDependentcomponenttype();
                        dependentDescriptor.dependentId = item.getDependentobjectid();
                        result.add(dependentDescriptor);
                    }
                }
            }
        }
        catch (Exception exception)
        {
            try
            {
                _appLogging.error(exception);
            }
            catch(Exception e) { }
        }
        return result;
    }
}
